import { Footer, Question, SelectLang, AvatarDropdown, AvatarName } from '@/components';
import { LinkOutlined } from '@ant-design/icons';
import type { Settings as LayoutSettings, PageLoading } from '@ant-design/pro-components';
import { SettingDrawer } from '@ant-design/pro-components';
import type { RunTimeLayoutConfig } from '@umijs/max';
import { history, Link } from '@umijs/max';
import defaultSettings from '../config/defaultSettings';
// import { currentUser as queryCurrentUser } from '@/services/ant-design-pro/api';
import React from 'react';
import { message, Input } from 'antd';
const isDev = process.env.NODE_ENV === 'development';
const loginPath = '/user/login';
const registerPath = '/user/register'
import { User, GetUserPermissions } from '@/api/userInfo'
const { Search } = Input;
/**
 * @see  https://umijs.org/zh-CN/plugins/plugin-initial-state
 * */
// 获取数据时候调用
export async function getInitialState() {
  // console.log('-----用户信息不应该每次刷新调用？考虑一下其他存储方式')
  // 如果不是登录页面，执行
  const { location } = history;
  const fetchUserInfo = async () => {
    try {
      // console.log(window.localStorage.getItem('token'))
      // 查看 token 是否存在
      if (window.localStorage.getItem('token')) {
        try {
          // 获取用户个人基础信息
          const info = await User(window.localStorage.getItem('token'));
          // 获取用户权限信息
          const data = await GetUserPermissions();
          // 如果在登陆中， 权限修改，刷新页面进行判断
          if (data.data.length === 0) {
            window.localStorage.removeItem('token')
            message.info("无权限")
            return
          }
          // console.log('app.tsx data.data', data.data)
          const remainder = info.results[0].id  % 10
          return {
            "userinfo": info.results[0],
            "name": info.results[0].username, //用户name
            "access": "admin",
            "permissionslist": data.data,
            "avatar": `/assets/img/avatar/Avatar0${remainder}.jpg`,
            // "avatar": "https://aos-cdn-image.amap.com/pp/avatar/8f1/93/02/1115145147.jpg"
            // "https://gw.alipayobjects.com/zos/rmsportal/BiazfanxmamNRoxxVxka.png" 
          };
        } catch (error) {
          history.push(loginPath)
          message.error("用户身份过期，请重新登录~")
        }
      } else {
        // 
        if (location.pathname === loginPath || location.pathname === registerPath) {
          return
        }
        history.push(loginPath)
        message.error("用户身份过期，请重新登录~")
      }
    } catch (error) {
      history.push(loginPath);
      message.error("用户身份过期，请重新登录~")
    }
    // console.log('-----------')
    return {
      // "username": "admin",
      // "age": 18
    };
  };

  if (location.pathname !== loginPath || location.pathname !== registerPath) {
    const currentUser = await fetchUserInfo();
    return {
      fetchUserInfo,
      currentUser,
      settings: defaultSettings as Partial<LayoutSettings>,
    };
  }
  return {
    fetchUserInfo,
    settings: defaultSettings as Partial<LayoutSettings>,
  };
}

// ProLayout 支持的api https://procomponents.ant.design/components/layout
export const layout: RunTimeLayoutConfig = ({ initialState, setInitialState }) => {
  return {
    actionsRender: () => [<Search placeholder="搜索更多佳立信息..." key="search" enterButton />, <Question key="doc" />, <SelectLang key="SelectLang" />],
    avatarProps: {
      src: initialState?.currentUser?.avatar,
      title: <AvatarName />,
      render: (_, avatarChildren) => {
        return <AvatarDropdown>{avatarChildren}</AvatarDropdown>;
      },
    },
    waterMarkProps: {
      content: initialState?.currentUser?.name,
    },
    footerRender: () => <Footer />,
    onPageChange: () => {
      const { location } = history;
      // console.log("location:",location)

      // 如果没有登录，重定向到 login
      if (!initialState?.currentUser && location.pathname !== loginPath) {
        // console.log("location:", location)
        history.push(loginPath);
      }
    },
    bgLayoutImgList: [
      {
        src: 'https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/D2LWSqNny4sAAAAAAAAAAAAAFl94AQBr',
        left: 85,
        bottom: 100,
        height: '303px',
      },
      {
        src: 'https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/C2TWRpJpiC0AAAAAAAAAAAAAFl94AQBr',
        bottom: -68,
        right: -45,
        height: '303px',
      },
      {
        src: 'https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/F6vSTbj8KpYAAAAAAAAAAAAAFl94AQBr',
        bottom: 0,
        left: 0,
        width: '331px',
      },
    ],

    // 如果是开发模式显示 openapi 
    // links: isDev
    //   ? [
    //     <Link key="openapi" to="/umi/plugin/openapi" target="_blank">
    //       <LinkOutlined />
    //       <span>OpenAPI 文档</span>
    //     </Link>,
    //   ]
    //   : [],
    menuHeaderRender: undefined,
    // 自定义 403 页面
    // unAccessible: <div>unAccessible</div>,
    // 增加一个 loading 的状态
    childrenRender: (children) => {
      if (initialState?.loading) return <PageLoading />;
      return (
        <>
          {children}
          {isDev && (
            <SettingDrawer
              disableUrlParams
              enableDarkTheme
              settings={initialState?.settings}
              onSettingChange={(settings) => {
                setInitialState((preInitialState) => ({
                  ...preInitialState,
                  settings,
                }));
              }}
            />
          )}
        </>
      );
    },
    ...initialState?.settings,
  };
};

/**
 * @name request 配置，可以配置错误处理
 * 它基于 axios 和 ahooks 的 useRequest 提供了一套统一的网络请求和错误处理方案。
 * @doc https://umijs.org/docs/max/request#配置
 */
export const request = {
  timeout: 6000,
  // 错误统一处理
  errorConfig: {
    errorHandler(err) {
      // console.log("response----", err)

      // 状态401权限认证 不成功
      if (err.request.status === 401) {
        window.localStorage.removeItem('token') //清除token

        const { location } = history;
        if (location.pathname !== registerPath) {
          setTimeout(() => {
            history.push('/user/login'); // 重定向到登录页面  
          }, 1500);
          message.error("用户令牌失效，请重新登录~"); // 显示错误消息 
        }
        return
      }
      // 状态码400 没有权限访问资源
      if (err.request.status === 400) {
        message.error("客户端请求的语法错误"); // 显示错误消息 
        return
      }
      // 状态码403 没有权限访问资源
      if (err.request.status === 403) {
        message.error("没有权限访问该资源~"); // 显示错误消息 
        return
      }
      // 状态码404 没有权限访问资源
      if (err.request.status === 404) {
        message.error("请求的资源不存在~"); // 显示错误消息 
        return
      }
      // 状态码500 没有权限访问资源
      if (err.request.status === 500) {
        message.error("服务器出错了~"); // 显示错误消息 
        return
      }
      message.error("网络繁忙，请稍后再试~")
    }
  },

  // 请求拦截器
  requestInterceptors: [
    (config) => {
      // 拦截请求配置，进行个性化处理。
      const token = window.localStorage.getItem('token') || ''
      if (token && config.url !== "/api/api-token-auth") {
        config.headers['token'] = token
      }
      if (token) {
        // config.headers['Authorization'] = `Token ${token}`; // 之前的 "rest_framework.authtoken",  # DRF自带的token认证
        config.headers['Authorization'] = `Bearer ${token}`;

        // JWT认证
      }
      return config
    },
  ],

  // 响应拦截器
  responseInterceptors: [
    (response) => {
      // 拦截响应数据，进行个性化处理
      // const { data } = response as unknown as ResponseStructure;

      // if (data?.success === false) {
      //   message.error('请求失败！');
      // }
      return response;
    },
  ],

};
